package utfpr.gang5.hermes.controledepresenca.dao;

import java.util.List;

import org.hibernate.Session;

import utfpr.gang5.hermes.controledepresenca.util.HibernateUtil;

public abstract class GenericCrud <T> implements Crud<T> {

	@Override
	public void salvar(T obj) throws CrudException{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		try {
			session.saveOrUpdate(obj);
		} catch (Exception e) {
			throw new CrudException(e.getMessage(), e);
		}
	}

	@Override
	public void excluir(T obj) throws CrudException{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		try {
			session.delete(obj);
		} catch (Exception e) {
			throw new CrudException(e.getMessage(), e);
		}
	}

	@SuppressWarnings("unchecked")
	public T carregar(Class<T> clazz, Long id) throws CrudException{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		try {
			Object obj = session.load(clazz, id);
			return (T) obj;
		} catch (Exception e) {
			throw new CrudException(e.getMessage(), e);
		} 		
	}

	@SuppressWarnings("unchecked")
	public List<T> carregarTodos(Class<T> clazz) throws CrudException{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		try {
			return session.createCriteria(clazz).list();
		} catch (Exception e) {
			throw new CrudException(e.getMessage(), e);
		} 	
	
	}

}
